<script setup lang="ts">
import PanelGroup from './components/PanelGroup.vue'
import Project from './components/Project.vue'
import { ElRow, ElCol, ElCard, ElSkeleton, ElSelect, ElOption, ElDatePicker, ElButton } from 'element-plus'
import { Echart } from '@/components/Echart'
import { pieOptions, barOptions, lineOptions, wordOptions, groupMonthlyOptions, oprOptions, groupDayOptions } from './echarts-data'
import { ref, reactive, computed, watch } from 'vue'
import dayjs from 'dayjs'
import {
  getUserAccessSourceApi,
  getMonthlySalesApi,
  getProjectApi,
  postPrjincApi,
  postGrpmonthApi,
  postOprincApi,
  postGrpdayApi
} from '@/api/dashboard/analysis'
import { getGroupListApi } from '@/api/group'
import type { ProjectIncome } from '@/api/dashboard/analysis/types'
import { set } from 'lodash-es'
import { EChartsOption } from 'echarts'
import { useI18n } from '@/hooks/web/useI18n'

const { t } = useI18n()

const panelGroupRef = ref<InstanceType<typeof PanelGroup> | null>(null)
const loading = ref(true)
const selectedYear = ref(new Date().getFullYear().toString())

// 操手筛选相关
const operatorYear = ref('')
const operatorGroup = ref('')
const groupOptions = ref<{ value: string; label: string }[]>([])
const operatorYearOptions = ref<{ value: string; label: string }[]>([])

// 初始化操手年份选项和默认值
const currentYearForOperator = new Date().getFullYear()
operatorYear.value = currentYearForOperator.toString()
for (let i = currentYearForOperator; i >= currentYearForOperator - 5; i--) {
  operatorYearOptions.value.push({ value: i.toString(), label: i.toString() + '年' })
}

// 小组日表筛选相关
const groupDayDate = ref(dayjs().format('YYYY-MM'))

// 获取日期范围显示文本
const dateRangeDisplay = computed(() => {
  if (panelGroupRef.value?.computedDateRange) {
    return panelGroupRef.value.computedDateRange.display + ' 数据总表'
  }
  return '2025/10/1-2025/10/15 数据总表'
})



const pieOptionsData = reactive<EChartsOption>(pieOptions) as EChartsOption

// 小组收益比例
const getUserAccessSource = async () => {
  // 从 PanelGroup 获取选中的日期范围，如果没有则使用默认日期范围
  const selectedDateRange = panelGroupRef.value?.selectedDateRange 
    ? panelGroupRef.value.selectedDateRange
    : [dayjs().subtract(1, 'month').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
  
  // fromDay 是开始日期，yearOrDay 是结束日期
  const fromDay = selectedDateRange[0]
  const yearOrDay = selectedDateRange[1]
  
  const res = await getUserAccessSourceApi({
    yearOrDay,
    fromDay
  }).catch(() => {})
  if (res && res.data) {
    // 定义颜色数组，对应不同小组
    const colors = ['#5470c6', '#ee6666', '#9a60b4', '#fac858', '#95de64']
    
    // 处理数据：支持 res.data 是数组或 res.data.items 是数组
    const data = Array.isArray(res.data) ? res.data : (res.data.items || [])
    
    set(
      pieOptionsData,
      'legend.data',
      data.map((v) => t(v.name))
    )
    set(pieOptionsData, 'series.0.data', data.map((v, index) => {
      return {
        name: t(v.name),
        value: v.value,
        itemStyle: {
          color: colors[index % colors.length]
        }
      }
    }))
  }
}



const lineOptionsData = reactive<EChartsOption>(lineOptions) as EChartsOption

//  数据总表
const getMonthlySales = async () => {
  const res = await getMonthlySalesApi({
    year: selectedYear.value
  }).catch(() => {})
  if (res && res.data) {
    // 处理数据：支持 res.data 是数组或 res.data.items 是数组
    const data = Array.isArray(res.data) ? res.data : (res.data.items || [])
    
    set(
      lineOptionsData,
      'xAxis.data',
      data.map((v) => t(v.name))
    )
    set(lineOptionsData, 'series', [
      // {
      //   name: t('analysis.estimate'),
      //   smooth: true,
      //   type: 'line',
      //   data: data.map((v) => v.estimate),
      //   animationDuration: 2800,
      //   animationEasing: 'cubicInOut'
      // },
      {
        name: t('analysis.actual'),
        smooth: true,
        type: 'line',
        itemStyle: {},
        data: data.map((v) => v.value),
        animationDuration: 2800,
        animationEasing: 'quadraticOut'
      }
    ])
  }
}
const wordOptionsData = reactive<EChartsOption>(wordOptions) as EChartsOption

// 参与项目
const getProject = async () => {
  const res = await getProjectApi().catch(() => {})
  if (res) {
    // 更新词云数据
    set(wordOptionsData, 'series.0.data', res.data.items.map((v) => ({
      name: v.symbol,
      value: v.id // 使用id作为权重值，你也可以根据需要调整
    })))
  }
}

// 项目历史及收益
const projectIncomeList = ref<ProjectIncome[]>([])
const getProjectIncome = async () => {
  // 从 PanelGroup 获取选中的日期范围，如果没有则使用默认日期范围
  const selectedDateRange = panelGroupRef.value?.selectedDateRange 
    ? panelGroupRef.value.selectedDateRange
    : [dayjs().subtract(1, 'month').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
  
  // fromDay 是开始日期，yearOrDay 是结束日期
  const fromDay = selectedDateRange[0]
  const yearOrDay = selectedDateRange[1]
  
  const res = await postPrjincApi({
    pagesize: 10,
    page: 1,
    yearOrDay,
    fromDay
  }).catch(() => {})
  if (res && res.data && res.data.items) {
    projectIncomeList.value = res.data.items
  }
}

// 小组月表
const groupMonthlyOptionsData = reactive<EChartsOption>(groupMonthlyOptions) as EChartsOption
const getGroupMonthly = async () => {
  const res = await postGrpmonthApi({
    year: operatorYear.value,
    grpid: operatorGroup.value || undefined
  }).catch(() => {})
  if (res && res.data && res.data.items) {
    // 假设返回的数据格式为数组，每个月有收入、利润、损耗三个字段
    const monthlyData = res.data.items
    set(groupMonthlyOptionsData, 'series.0.data', monthlyData.map((v: any) => v.income || v.revenue || 0))
    set(groupMonthlyOptionsData, 'series.1.data', monthlyData.map((v: any) => v.profit || 0))
    set(groupMonthlyOptionsData, 'series.2.data', monthlyData.map((v: any) => v.loss || v.expenditure || 0))
  }
}

// 操手收益比例
const operatorPieOptionsData = reactive<EChartsOption>(oprOptions) as EChartsOption
const getOperatorRevenue = async () => {
  const res = await postOprincApi({
    year: operatorYear.value,
    grpid: operatorGroup.value || undefined
  }).catch(() => {})
  if (res && res.data) {
    const colors = ['#5470c6', '#ee6666', '#9a60b4', '#fac858', '#95de64']
    const data = Array.isArray(res.data) ? res.data : res.data.items || []
    set(operatorPieOptionsData, 'legend.data', data.map((v: any) => v.name || v.operatorName))
    set(operatorPieOptionsData, 'series.0.data', data.map((v: any, index: number) => {
      return {
        name: v.name || v.operatorName,
        value: v.value || v.revenue || 0,
        itemStyle: {
          color: colors[index % colors.length]
        }
      }
    }))
  }
}

// 获取小组列表
const getGroups = async () => {
  const res = await getGroupListApi({page: 1, pagesize: 0}).catch(() => {})
  if (res && res.data) {
    groupOptions.value = (res.data.items || res.data).map((v: any) => ({
      value: v.id || v.value,
      label: v.name || v.label
    }))
  }
}

// 小组日表
const groupDayOptionsData = reactive<EChartsOption>(groupDayOptions) as EChartsOption
const getGroupDay = async () => {
  const res = await postGrpdayApi({
    month: groupDayDate.value,
    grpid:operatorGroup.value || undefined
  }).catch(() => {})
  if (res && res.data && res.data.items) {
    const dailyData = res.data.items
    set(groupDayOptionsData, 'xAxis.data', dailyData.map((v: any) => v.day || v.date))
    set(groupDayOptionsData, 'series.0.data', dailyData.map((v: any) => v.loss || v.expenditure || 0))
    set(groupDayOptionsData, 'series.1.data', dailyData.map((v: any) => v.profit || 0))
    set(groupDayOptionsData, 'series.2.data', dailyData.map((v: any) => v.income || v.revenue || 0))
  }
}

// 筛选操作
const handleFilter = () => {
  getOperatorRevenue()
  getGroupMonthly()
  // 更新小组日表的年份，格式为 YYYY-MM，使用当前月份
  const currentMonth = dayjs().format('MM')
  groupDayDate.value = `${operatorYear.value}-${currentMonth}`
  // 触发小组日表接口
  getGroupDay()
}

// 重置操作
const handleReset = () => {
  operatorYear.value = currentYearForOperator.toString()
  operatorGroup.value = ''
  getOperatorRevenue()
  getGroupMonthly()
  // 更新小组日表的年份，格式为 YYYY-MM，使用当前月份
  const currentMonth = dayjs().format('MM')
  groupDayDate.value = `${operatorYear.value}-${currentMonth}`
  // 触发小组日表接口
  getGroupDay()
}

const getAllApi = async () => {
  await Promise.all([getUserAccessSource(),  getProject(), getProjectIncome(), getGroupMonthly(), getGroups(), getOperatorRevenue(), getGroupDay()])
  loading.value = false
}



// 监听 PanelGroup 的日期变化
watch(() => panelGroupRef.value?.selectedDate, () => {
  if (panelGroupRef.value) {
    getProjectIncome()
  }
}, { deep: true })

// 处理 PanelGroup 的筛选事件
const handlePanelGroupFilter = () => {
  // 更新选中年份
  if (panelGroupRef.value?.selectedDate) {
    selectedYear.value = dayjs(panelGroupRef.value.selectedDate).format('YYYY')
  }
  // 调用 getUserAccessSource 和 getProjectIncome，它们会自动从 PanelGroup 获取选中日期
  getUserAccessSource()
  getProjectIncome()
}

getAllApi()
</script>

<template>
  <div class="analysis-container">
    <PanelGroup ref="panelGroupRef" @filter="handlePanelGroupFilter" />
    <ElRow :gutter="0" justify="space-between">
      <ElCol :span="24">
      <ElCard shadow="never">
        <template #header>
          <div class="card-header">
            <span>{{ dateRangeDisplay }}</span>
          </div>
        </template>
        <ElSkeleton :loading="loading" animated :rows="4">
          <Echart :options="lineOptionsData" :height="350" />
        </ElSkeleton>
      </ElCard>
    </ElCol>
    <ElCol :xl="10" :lg="10" :md="24" :sm="24" :xs="24" class="group-revenue-col">
      <ElCard shadow="never">
        <template #header>
          <div class="card-header">
            <span>小组收益比例</span>
          </div>
        </template>
        <ElSkeleton :loading="loading" animated>
          <Echart :options="pieOptionsData" :height="400" />
        </ElSkeleton>
      </ElCard>
    </ElCol>
    <ElCol :xl="14" :lg="14" :md="24" :sm="24" :xs="24" class="project-revenue-col">
      <ElCard shadow="never">
        <template #header>
          <div class="card-header">
            <span>项目历史及收益</span>
          </div>
        </template>
        <ElSkeleton :loading="loading" animated :rows="4">
          <div class="project-income-list" style="height: 300px; display: flex; flex-direction: column;">
            <div class="project-row" v-for="(item, index) in projectIncomeList" :key="index">
              <div class="project-column  center-align">
                <div class="project-name">{{ item.symbol }}</div>
                <div class="project-date">{{ item.airdropTime || item.airdropTime }}</div>
              </div>
              <div class="project-column center-align">
                <div class="value">{{ item.accNum }}</div>
                <div class="label">参与账号数目</div>
              </div>
              <div class="project-column  center-align">
                <div class="value">${{ item.incTotal.toFixed(2) }}</div>
                <div class="label">空投收益总数</div>
              </div>
              <div class="project-column  center-align">
                <div class="value">${{ item.incAver.toFixed(2) }}</div>
                <div class="label">平均账号收益</div>
              </div>
            </div>
          </div>
        </ElSkeleton>
      </ElCard>
    </ElCol>

    <!-- 小组数据面板整体区域 -->
    <ElCol :span="24" class="group-data-panel-wrapper">
      <ElCard shadow="never" class="group-data-panel-card">
        <!-- 筛选区域 -->
        <template #header>
          <div class="group-data-panel-header">
            <h2 class="panel-title">小组数据面板</h2>
            <div class="filter-container">
              <ElSelect v-model="operatorYear" placeholder="选择年份" class="filter-select">
                <ElOption
                  v-for="option in operatorYearOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </ElSelect>
              <ElSelect v-model="operatorGroup" placeholder="选择小组" clearable class="filter-select">
                <ElOption
                  v-for="option in groupOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </ElSelect>
              <ElButton type="primary" @click="handleFilter">筛选</ElButton>
              <ElButton @click="handleReset">重置</ElButton>
            </div>
          </div>
        </template>
        
        <!-- 图表区域 -->
        <ElSkeleton :loading="loading" animated :rows="4">
          <ElRow :gutter="0" class="chart-row">
            <ElCol :xl="10" :lg="10" :md="24" :sm="24" :xs="24" class="chart-col-left">
              <div class="chart-item">
                <div class="chart-header">操手收益比例</div>
                <Echart :options="operatorPieOptionsData" :height="300" />
              </div>
            </ElCol>
            <ElCol :xl="14" :lg="14" :md="24" :sm="24" :xs="24" class="chart-col-right">
              <div class="chart-item">
                <div class="chart-header">小组月表</div>
                <Echart :options="groupMonthlyOptionsData" :height="300" />
              </div>
            </ElCol>
          </ElRow>
        </ElSkeleton>
      </ElCard>
    </ElCol>
    <!-- 小组日表 -->
    <ElCol :span="24">
      <ElCard shadow="never" class="group-data-panel-card">
        <!-- 筛选区域 -->
        <template #header>
          <div class="group-data-panel-header">
            <h2 class="panel-title">小组日表</h2>
            <div class="filter-container">
              <ElDatePicker
                v-model="groupDayDate"
                type="month"
                format="YYYY/MM"
                value-format="YYYY-MM"
                placeholder="选择月份"
                @change="getGroupDay"
              />
            </div>
          </div>
        </template>
        <!-- 小组日表 -->
        <ElSkeleton :loading="loading" animated :rows="4">
          <Echart :options="groupDayOptionsData" :height="400" />
        </ElSkeleton>
      </ElCard>
    </ElCol>
    <!-- <Project /> -->
    <ElCol :span="24">
      <ElCard shadow="never">
        <ElSkeleton :loading="loading" animated>
          <Echart :options="wordOptionsData" :height="400" />
        </ElSkeleton>
      </ElCard>
    </ElCol>
  </ElRow>
  </div>
</template>

<style scoped>
/* 设置页面背景为白色 */
.analysis-container {
  background-color: #fff;
  min-height: 100vh;
}

:deep(.el-card) {
  background-color: #fff;
}

:deep(.el-row) {
  background-color: #fff;
}

:deep(.el-card__body) {
  background-color: #fff;
}

:deep(.el-col) {
  padding: 0 !important;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.group-data-panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.panel-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.filter-container {
  display: flex;
  gap: 15px;
  align-items: center;
}

.filter-select {
  width: 150px;
}

.filter-row {
  margin-bottom: 0;
}

/* 为小组收益比例和项目历史及收益卡片添加无缝拼接效果 */
.group-revenue-col :deep(.el-card) {
  border: 1px solid #ebeef5;
  border-right: none;
  border-radius: 4px 0 0 4px;
}

.project-revenue-col :deep(.el-card) {
  border: 1px solid #ebeef5;
  border-left: 1px solid #ebeef5;
  border-radius: 0 4px 4px 0;
}


/* 只针对小组数据面板的margin-top */
.group-data-panel-wrapper {
  margin-top: 30px;
  position: relative;
}

/* 在margin-top上方添加一条背景色条 */
.group-data-panel-wrapper::before {
  content: '';
  position: absolute;
  top: -30px;
  left: 0;
  right: 0;
  height: 30px;
  background-color: #f0f0f0;
}

.chart-row {
  margin: 0;
  align-items: stretch;
}

.chart-col-left {
  border-right: 1px solid #ebeef5;
  display: flex;
}

.chart-col-left > div {
  width: 100%;
}

.chart-col-right {
  display: flex;
}

.chart-col-right > div {
  width: 100%;
}

.chart-item {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chart-header {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 15px;
}

/* 小组数据面板卡片边框 */
.group-data-panel-card :deep(.el-card) {
  border: 1px solid #ebeef5;
}

.project-income-list {
  padding: 10px 0;
}

.project-row {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f2f5;
  transition: background-color 0.2s;
}

.project-row:hover {
  background-color: #fafafa;
}

.project-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.project-column.right-align {
  align-items: flex-end;
}

.project-column.center-align {
  align-items: center;
}

.project-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.project-date {
  font-size: 13px;
  color: #666666;
}

.project-column .value {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.project-column .label {
  font-size: 12px;
  color: #666666;
}

/* 移动端响应式样式 */
@media (max-width: 768px) {
  .group-data-panel-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .panel-title {
    width: auto;
    text-align: left;
    font-size: 14px;
  }

  /* 只针对小组数据面板的标题 */
  .group-data-panel-wrapper .group-data-panel-header .panel-title {
    font-size: 28px;
    margin-top: -5px;
  }

  .filter-container {
    flex-wrap: nowrap;
    justify-content: flex-start;
    gap: 5px;
    width: 100%;
  }

  .filter-select {
    width: auto;
    min-width: 100px;
    flex-shrink: 1;
  }

  .filter-container :deep(.el-select:first-of-type) {
    min-width: 97px;
  }

  .filter-container :deep(.el-select) {
    font-size: 12px;
  }

  .filter-container :deep(.el-select .el-input__inner) {
    height: 28px;
    font-size: 12px;
    padding: 0 25px 0 8px;
  }

  .filter-container :deep(.el-select .el-input__suffix) {
    height: 28px;
  }

  .filter-container :deep(.el-button) {
    flex-shrink: 0;
    white-space: nowrap;
    height: 28px;
    padding: 7px 12px;
    font-size: 12px;
  }

  .filter-container :deep(.el-button:last-child) {
    margin-left: 0px;
  }

  .chart-row {
    margin: 0;
  }

  .chart-col-left {
    border-right: none;
    border-bottom: 1px solid #ebeef5;
    margin-bottom: 0;
  }

  .group-revenue-col :deep(.el-card) {
    border: 1px solid #ebeef5;
    border-radius: 4px;
  }

  .project-revenue-col :deep(.el-card) {
    border: 1px solid #ebeef5;
    border-radius: 4px;
  }

  .project-row {
    flex-wrap: wrap;
    justify-content: center;
  }

  .project-column {
    min-width: 45%;
    margin-bottom: 10px;
  }

  .project-column.center-align {
    align-items: center;
  }
}
</style>
